package com.efounder.activity;

import android.animation.Animator;
import android.animation.ValueAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Path;
import android.graphics.PathMeasure;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.core.xml.StubObject;
import com.efounder.adapter.ScrollAdapter;
import com.efounder.addressselector.BottomDialog;
import com.efounder.addressselector.OnAddressSelectedListener;
import com.efounder.addressselector.model.City;
import com.efounder.addressselector.model.County;
import com.efounder.addressselector.model.Province;
import com.efounder.addressselector.model.Street;
import com.efounder.anim.HesitateInterpolator;
import com.efounder.bean.Address;
import com.efounder.bean.Collection;
import com.efounder.bean.CommentDatas;
import com.efounder.bean.DetailsDatas;
import com.efounder.bean.GoodSkusBean;
import com.efounder.chat.activity.BaseActivity;
import com.efounder.frame.manager.AppLoginManager;
import com.efounder.frame.manager.UrlSchemeManager;
import com.efounder.chat.struct.StructFactory;
import com.efounder.chat.utils.ChatActivitySkipUtil;
import com.efounder.chat.utils.CommonThreadPoolUtils;
import com.efounder.chat.widget.BadgeView;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.fragment.ProductDetailsFragment;
import com.efounder.frame.activity.EFTransformFragmentActivity;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.frame.utils.EFFrameUtils;
import com.efounder.http.EFHttpRequest;
import com.efounder.message.struct.IMStruct002;
import com.efounder.mobilemall.R;
import com.efounder.util.LoadingDataUtilBlack;
import com.efounder.utils.GlideImageLoader;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.ResStringUtil;
import com.efounder.utils.StatusBarUtil;
import com.efounder.view.AniManager;
import com.efounder.view.GradationScrollView;
import com.efounder.view.ProductSkuDialog;
import com.efounder.view.ScrollViewContainer;
import com.efounder.view.pop.MallPopManager;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.pansoft.openplanet.util.TCMathUtil;
import com.utilcode.util.SizeUtils;
import com.utilcode.util.TimeUtils;
import com.utilcode.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.CART_AMOUNT_URL;
import static com.efounder.utils.MallRequestUtil.GOOD_ADDTOCART_URL;
import static com.efounder.utils.MallRequestUtil.GOOD_COLLECT_AOR;
import static com.efounder.utils.MallRequestUtil.GOOD_COMMENT_URL;

/**
 * Created by wei on 2018/1/16/016.
 * 商城详情页
 *
 * @author 隗德彪
 */

public class ProductDetailsActivity extends BaseActivity implements GradationScrollView.ScrollViewListener, View.OnClickListener {
    private String TAG = this.getClass().getSimpleName();
    ImageView detail_back;
    GradationScrollView scrollView;
    RelativeLayout iv;
    LinearLayout llTitle;
    LinearLayout ll_good_detail_service;
    LinearLayout llOffset;
    ImageView iv_shoucang;
    TextView tv_shoucang;
    ScrollViewContainer container;
    TextView tvGoodTitle;
    TextView tvGoodComment;
    TextView tvGoodDetails;
    LinearLayout llGoodTitle;
    LinearLayout llGoodComment;
    LinearLayout llGoodDetails;
    View goods_line;
    View comment_line;
    View details_line;
    RecyclerView cRecyclerView;
    RadioGroup radioGroup;
    RadioGroup radioGroupGone;
    RadioButton radioButton1;
    RadioButton radioButton2;
    RadioButton radioButton3;
    RadioButton radioButton4;
    ViewPager viewPager;
    LinearLayout goodsComment;
    RelativeLayout peisong;
    //    guige)
//    RelativeLayout guige;
    RelativeLayout reChooseSku;
    TextView tvChooseSkuHint;
    TextView tvSkuAttrs;
    TextView shopCart;
    TextView buyNow;
    TextView tvAddress;
    //    tv_specifications)
//    TextView tvSpecifications;
    TextView currentPrice;
    TextView tvOriginPrice;
    TextView title;
    TextView tv_description;
    TextView commentCount;
    TextView commentPercent;
    LinearLayout mLinearLayout;
    ImageView cartIcon;
    LinearLayout ll_shopcart;
    LinearLayout llNetworkErrorView;
    FrameLayout fl_content;
    ImageView iv_good_detai_share;
    TextView tvWinTreasure;
    LinearLayout llGoodDetailService;
    ConstraintLayout llWinTreasureProgress;
    TextView tvProgress;
    TextView tvProgressNum;
    ProgressBar progressbar;
    TextView tvNetworkReload;
    /**
     * 客服按钮
     */
    LinearLayout ll_custom_service;
    /*夺宝商品类型*/
    public static final String GOOD_TYPE_TREASURE = "08";
    /*虚拟商品类型*/
    public static final String GOOD_TYPE_VIRTUAL = "01";
    /*新的虚拟商品类型*/
    public static final String GOOD_TYPE_NEW_VIRTUAL = "0102";
    /* 限时抢购商品类型 */
    public static final String GOOD_TYPE_TIME_TO_BUY = "09";
    /* 限时抢购商品的状态*/
    //限时抢购状态未开始
    public static int STATUS_NO_START = 0;
    //限时抢购状态抢购中
    public static int STATUS_BUYING = 1;
    //抢购结束
    public static int STATUS_BUG_END = 2;
    private PopupWindow confirmPopup;
    private Address defaultAddress = null;
    private Address targetAddress = null;
    private ProductSkuDialog dialog;
    private GoodSkusBean selectedSku;
    private int itemNum = 1;
    private List<Address> addresses = new ArrayList<>();
    private CommentDatas commentDatas;
    private double mCurrentPrice;
    private Bitmap bitmap = null;

    private int height;
    private ProductDetailsFragment f1;
    private ProductDetailsFragment f2;
    private boolean isLove = false;
    private GlideImageLoader imageLoader;
    int currPosition = 0; // 当前滑动到了哪一页
    boolean canJump = false;
    boolean canLeft = true;
    private int mNum = 0;
    private DetailsDatas detailsDatas;
    /**
     * 商品的id
     */
    private String goodbh, goodStatus;
    private AniManager mAniManager;
    private BadgeView buyNumView;
    private ImageView buyImg;
    private int num;
    private ArrayList<String> list;
    private int count;
    private boolean hasSku = false;
    /*是否是夺宝商品*/
    private boolean isTreasureGood = false;
    float[] mCurrentPosition = new float[2];
    /**
     * //当前滑动到y轴的点
     */
    private int currentY = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_product_details);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
        StatusBarUtil.setStatusBarTranslucent(this, false);
        initView();

        initParams();//设置布局参数
        imageLoader = new GlideImageLoader();
        //暂不请求地址
//        initAddress();

        //消息跳转
        if (getIntent().hasExtra("stubObject")) {
            StubObject stubObject = (StubObject) getIntent().getSerializableExtra("stubObject");
            IMStruct002 imStruct002 = (IMStruct002) stubObject.getStubTable().get("imStruct002");
            String message = imStruct002.getMessage();
            JSONObject jsonObject = null;
            try {
                jsonObject = new JSONObject(message);
                goodbh = jsonObject.getString("goodId");
            } catch (Exception e) {
                e.printStackTrace();
            }

            goodStatus = "1";
        }//URLscheme 进入
        else if (UrlSchemeManager.hasUrlScheme(getIntent())) {
            if (!AppLoginManager.isUserLogined()) {
                AppLoginManager.showNotLogInDialog(this);
                setSwipeBackEnable(false);
                return;
            }
            goodbh = getIntent().getData().getQueryParameter("goodbh") + "";
        } else {
            //intent 进入
            goodbh = getIntent().getStringExtra("goodbh");
            goodStatus = getIntent().getStringExtra("goodStatus");
        }


        container = new ScrollViewContainer(getApplicationContext());

        initListeners();//设置监听
        initAnimation();//设置加入购物车动画


    }

    private void initView() {
        detail_back = (ImageView) findViewById(R.id.detail_back);
        scrollView = (GradationScrollView) findViewById(R.id.scrollview);
        iv = (RelativeLayout) findViewById(R.id.iv);
        llTitle = (LinearLayout) findViewById(R.id.ll_good_detail);
        ll_good_detail_service = (LinearLayout) findViewById(R.id.ll_good_detail_service);
        llOffset = (LinearLayout) findViewById(R.id.ll_offset);
        iv_shoucang = (ImageView) findViewById(R.id.iv_shoucang);
        tv_shoucang = (TextView) findViewById(R.id.tv_shoucang);
        container = (ScrollViewContainer) findViewById(R.id.sv_container);
        tvGoodTitle = (TextView) findViewById(R.id.goods);
        tvGoodComment = (TextView) findViewById(R.id.comment);
        tvGoodDetails = (TextView) findViewById(R.id.details);
        llGoodTitle = (LinearLayout) findViewById(R.id.goods_ll);
        llGoodComment = (LinearLayout) findViewById(R.id.comment_ll);
        llGoodDetails = (LinearLayout) findViewById(R.id.details_ll);
        goods_line = findViewById(R.id.goods_line);
        comment_line = findViewById(R.id.comment_line);
        details_line = findViewById(R.id.details_line);
        cRecyclerView = (RecyclerView) findViewById(R.id.comments);
        radioGroup = (RadioGroup) findViewById(R.id.radio);
        radioGroupGone = (RadioGroup) findViewById(R.id.radio_gone);
        radioButton1 = (RadioButton) findViewById(R.id.btn1);
        radioButton2 = (RadioButton) findViewById(R.id.btn2);
        radioButton3 = (RadioButton) findViewById(R.id.btn3);
        radioButton4 = (RadioButton) findViewById(R.id.btn4);
        viewPager = (ViewPager) findViewById(R.id.detail_viewpager);
        goodsComment = (LinearLayout) findViewById(R.id.goodscomment);
        peisong = (RelativeLayout) findViewById(R.id.peisong);
        //    guige)
//    RelativeLayout guige;
        reChooseSku = (RelativeLayout) findViewById(R.id.re_choose_sku);
        tvChooseSkuHint = (TextView) findViewById(R.id.tv_choose_sku_hint);
        tvSkuAttrs = (TextView) findViewById(R.id.tv_sku_attrs);
        shopCart = (TextView) findViewById(R.id.tv_shopcart);
        buyNow = (TextView) findViewById(R.id.tv_buy);
        tvAddress = (TextView) findViewById(R.id.tv_address);
        //    tv_specifications)
//    TextView tvSpecifications;
        currentPrice = (TextView) findViewById(R.id.currentPrice);
        tvOriginPrice = (TextView) findViewById(R.id.tv_origin_price);
        title = (TextView) findViewById(R.id.title);
        tv_description = (TextView) findViewById(R.id.tv_description);
        commentCount = (TextView) findViewById(R.id.commentCount);
        commentPercent = (TextView) findViewById(R.id.commentPercent);
        mLinearLayout = (LinearLayout) findViewById(R.id.main_linear);
        cartIcon = (ImageView) findViewById(R.id.cart);
        ll_shopcart = (LinearLayout) findViewById(R.id.ll_shopcart);
        llNetworkErrorView = (LinearLayout) findViewById(R.id.ll_network_error);
        fl_content = (FrameLayout) findViewById(R.id.fl_content);
        iv_good_detai_share = (ImageView) findViewById(R.id.iv_good_detai_share);
        tvWinTreasure = (TextView) findViewById(R.id.tv_win_treasure);
        llGoodDetailService = (LinearLayout) findViewById(R.id.ll_good_detail_bottom);
        llWinTreasureProgress = (ConstraintLayout) findViewById(R.id.ll_win_treasure_progress);
        tvProgress = (TextView) findViewById(R.id.tv_progress);
        tvProgressNum = (TextView) findViewById(R.id.tv_progress_num);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        tvNetworkReload = (TextView) findViewById(R.id.tv_network_reload);
        ll_custom_service = (LinearLayout) findViewById(R.id.ll_custom_service);
    }

    private void initBadge() {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        MallRequestUtil.getRequest(TAG, CART_AMOUNT_URL, map, new MallRequestUtil.MallRequestCallback() {

            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.has("goodTotalCount")) {
                        count = jsonObject.getInt("goodTotalCount");
                        if (count > 0) {
                            buyNumView.setText(count + "");
                            buyNumView.show();
                        } else {
                            buyNumView.hide();
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFail(String error) {
//                LogUtils.e("请求badge--" + error);
            }
        });
    }

    private void initAnimation() {
        //动画实例
        mAniManager = new AniManager();
        //把这个数字标签放在购物车图标上
        buyNumView = new BadgeView(this, cartIcon);
        buyNumView.setBadgePosition(BadgeView.POSITION_RIGHT);
        buyNumView.setTextColor(Color.WHITE);//数字颜色
        buyNumView.setBadgeBackgroundColor(Color.RED);//背景颜色
        buyNumView.setTextSize(9);//数字大小
    }

    private void initParams() {
        llTitle.setAlpha(0);
        //透明状态栏
//        StatusBarUtil.setTranslucentForImageView(this, llOffset);
        LinearLayout.LayoutParams params1 = (LinearLayout.LayoutParams) llOffset.getLayoutParams();
        params1.setMargins(0, -StatusBarUtil.getStatusBarHeight(this) / 4, 0, 0);
        llOffset.setLayoutParams(params1);

        //设置图片布局的参数
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) iv.getLayoutParams();
        params.height = getScreenWidth(this) / 9 * 10;
        iv.setLayoutParams(params);
    }

    /**
     * 启动动画
     *
     * @param v
     */
    public void startAnim(View v, final int goodTotalCount) {
        if (v == null) {
            buyNumView.setText(goodTotalCount + "");
            buyNumView.show();
        } else {
            int[] endLoc = new int[2];
            int[] startLoc = new int[2];
            v.getLocationInWindow(startLoc);// 获取购买按钮的在屏幕的X、Y坐标（动画开始的坐标）
            cartIcon.getLocationInWindow(endLoc);// 这是用来存储动画结束位置，也就是购物车图标的X、Y坐标
            // buyImg是动画的图片
            buyImg = new ImageView(this);
            if (bitmap == null) {
                buyNumView.setText(goodTotalCount + "");
                buyNumView.show();
                return;
            }
            buyImg.setImageBitmap(bitmap);
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(100, 100);
            fl_content.addView(buyImg, params);

            // 得到父布局的起始点坐标（用于辅助计算动画开始/结束时的点的坐标）
            int[] parentLocation = new int[2];
            fl_content.getLocationInWindow(parentLocation);

            // 开始掉落的商品的起始点：商品起始点-父布局起始点+该商品图片的一半
            float startX = startLoc[0] - parentLocation[0] + v.getWidth() / 2;
            float startY = startLoc[1] - parentLocation[1] + v.getHeight() / 2;

            // 商品掉落后的终点坐标：购物车起始点-父布局起始点+购物车图片的1/5
            float toX = endLoc[0] - parentLocation[0] + cartIcon.getWidth() / 5;
            float toY = endLoc[1] - parentLocation[1];

            // 开始绘制贝塞尔曲线
            Path path = new Path();
            // 移动到起始点（贝塞尔曲线的起点）
            path.moveTo(startX, startY);
            // 使用二阶贝塞尔曲线：注意第一个起始坐标越大，贝塞尔曲线的横向距离就会越大，一般按照下面的式子取即可
            path.quadTo((startX + toX) / 2, startY - 800, toX, toY);
            // mPathMeasure用来计算贝塞尔曲线的曲线长度和贝塞尔曲线中间插值的坐标，如果是true，path会形成一个闭环
            final PathMeasure mPathMeasure = new PathMeasure(path, false);

            // 属性动画实现（从0到贝塞尔曲线的长度之间进行插值计算，获取中间过程的距离值）
            ValueAnimator valueAnimator = ValueAnimator.ofFloat(0, mPathMeasure.getLength());
            valueAnimator.setDuration(1000);

            // 加速线性插值器
            valueAnimator.setInterpolator(new HesitateInterpolator());
            valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    // 当插值计算进行时，获取中间的每个值，
                    // 这里这个值是中间过程中的曲线长度（下面根据这个值来得出中间点的坐标值）
                    float value = (Float) animation.getAnimatedValue();
                    // 获取当前点坐标封装到mCurrentPosition
                    // boolean getPosTan(float distance, float[] pos, float[] tan) ：
                    // 传入一个距离distance(0<=distance<=getLength())，然后会计算当前距离的坐标点和切线，pos会自动填充上坐标，这个方法很重要。
                    // mCurrentPosition此时就是中间距离点的坐标值
                    mPathMeasure.getPosTan(value, mCurrentPosition, null);
//                    LogUtils.d("位移", mCurrentPosition[0] +" "+ mCurrentPosition[1]);
                    // 移动的商品图片（动画图片）的坐标设置为该中间点的坐标
                    buyImg.setTranslationX(mCurrentPosition[0]);
                    buyImg.setTranslationY(mCurrentPosition[1]);
                }
            });

            // 开始执行动画
            valueAnimator.start();
            // 动画结束后的处理
            valueAnimator.addListener(new Animator.AnimatorListener() {
                @Override
                public void onAnimationStart(Animator animation) {
                }

                @Override
                public void onAnimationEnd(Animator animation) {
                    // 购物车商品数量加1
                    buyNumView.setText(goodTotalCount + "");
                    buyNumView.show();
                    // 把执行动画的商品图片从父布局中移除
                    fl_content.removeView(buyImg);
                }

                @Override
                public void onAnimationCancel(Animator animation) {
                }

                @Override
                public void onAnimationRepeat(Animator animation) {
                }
            });
        }
    }

    private void setIndicator(int width, int index, boolean able) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(width, 20);
        layoutParams.leftMargin = 30;
        View childAt = mLinearLayout.getChildAt(index);
        childAt.setLayoutParams(layoutParams);
        childAt.setEnabled(able);
    }

    //显示第一个fragment
    private void initFragment1() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (f1 == null) {
            f1 = ProductDetailsFragment.newInstance(detailsDatas.getGood().getGoodUrl());
        }
        transaction.replace(R.id.framelayout, f1);
        transaction.commit();
    }

    private void initFragment2() {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        if (f2 == null) {
            f2 = ProductDetailsFragment.newInstance(detailsDatas.getGood().getGoodUrl());
        }
        transaction.replace(R.id.framelayout, f2);
        transaction.commit();
    }

    public int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    public int getScreenWidth(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.widthPixels;
    }

    private void initListeners() {

        //获取图片布局的高度，并监听
        ViewTreeObserver vto = iv.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                llTitle.getViewTreeObserver().removeGlobalOnLayoutListener(
                        this);
                height = iv.getHeight();
                scrollView.setScrollViewListener(ProductDetailsActivity.this);
            }
        });

        //图文详情布局的点击事件
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == radioButton1.getId()) {
                    initFragment1();
                    radioButton3.setChecked(true);
                } else if (checkedId == radioButton2.getId()) {
                    initFragment2();
                    radioButton4.setChecked(true);
                }
            }
        });
        //图文详情布局的点击事件（隐藏）
        radioGroupGone.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == radioButton3.getId()) {
                    initFragment1();
                    radioButton1.setChecked(true);
                } else if (checkedId == radioButton4.getId()) {
                    initFragment2();
                    radioButton2.setChecked(true);
                }
            }
        });
        llGoodTitle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                comment_line.setVisibility(View.INVISIBLE);
                details_line.setVisibility(View.INVISIBLE);
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        scrollView.scrollTo(0, 0);
                    }
                });
            }
        });
        llGoodComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                comment_line.setVisibility(View.VISIBLE);
                details_line.setVisibility(View.INVISIBLE);
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        int[] location1 = new int[2];
                        int[] location2 = new int[2];
                        goodsComment.getLocationOnScreen(location1);
                        llOffset.getLocationOnScreen(location2);
                        int yPosition1 = location1[1] - llTitle.getMeasuredHeight();
                        int yPosition2 = location2[1];
                        int offset = currentY + yPosition1;
                        scrollView.scrollTo(0, Math.abs(offset));
                        tvGoodTitle.setAlpha(1);
                        tvGoodComment.setAlpha(1);
                        tvGoodDetails.setAlpha(1);
                    }
                });
            }
        });

        llGoodDetails.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                scrollView.post(new Runnable() {
                    @Override
                    public void run() {
                        JumpToDetails();
                    }
                });
            }
        });

        detail_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        //商品图片的滑动监听
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                if (position == (detailsDatas.getGood().getPictures().size() - 1)) {
                    if (positionOffset > 0.1) {
                        canJump = true;

                    } else if (positionOffset <= 0.1 && positionOffset > 0) {
                        canJump = false;
                    }
                    canLeft = false;
                } else {
                    canLeft = true;
                }
            }

            @Override
            public void onPageSelected(int position) {
                currPosition = position;
                if (position < detailsDatas.getGood().getPictures().size()) {
                    //设置宽度并设置是否是当前选中状态
                    setIndicator(20, mNum, false);
                    setIndicator(60, position, true);
                    mNum = position;
                }

            }

            @Override
            public void onPageScrollStateChanged(int state) {
                if (currPosition == (detailsDatas.getGood().getPictures().size() - 1) && !canLeft) {
                    if (state == ViewPager.SCROLL_STATE_SETTLING) {
                        if (canJump) {
                            JumpToDetails();
                        }
                        new Handler().post(new Runnable() {
                            @Override
                            public void run() {
                                // 在handler里调用setCurrentItem才有效
                                viewPager.setCurrentItem(detailsDatas.getGood().getPictures().size() - 1);
                            }
                        });
                    }
                }
            }
        });

        //分享商品
        iv_good_detai_share.setOnClickListener(this);
        tvNetworkReload.setOnClickListener(this);
    }

    //跳转到图文详情
    private void JumpToDetails() {
        scrollView.post(new Runnable() {
            @Override
            public void run() {
                int[] location = new int[2];
                int goodsCommentHeight = goodsComment.getMeasuredHeight();
                int skuChooseHeight = reChooseSku.getMeasuredHeight();
                int cRecyclerViewHeight = cRecyclerView.getMeasuredHeight();
                tvGoodComment.getLocationInWindow(location);
                int offset;
                if (cRecyclerView.getVisibility() == View.VISIBLE) {
                    offset = scrollView.getMeasuredHeight() + 2 * skuChooseHeight + cRecyclerViewHeight / 2;
                } else {
                    offset = scrollView.getMeasuredHeight();
                }

                if (offset < 0) {
                    offset = 0;
                }
                scrollView.scrollTo(0, offset);
                tvGoodTitle.setAlpha(1);
                tvGoodComment.setAlpha(1);
                tvGoodDetails.setAlpha(1);
            }
        });
    }


    //滑动监听，滑动变色 + 上滑悬停 + 滑动关联
    @Override
    public void onScrollChanged(final GradationScrollView scrollView, int x, int y,
                                int oldx, int oldy) {
        currentY = y;
        if (y < 0) {   //设置标题的背景颜色
            llTitle.setAlpha(0);
        } else if (y >= 0 && y <= height) { //滑动距离小于banner图的高度时，设置背景和字体颜色颜色透明度渐变
            float scale = (float) y / height * 3;
            float alpha = (255 * scale);
            tvGoodTitle.setAlpha(scale);
            tvGoodComment.setAlpha(scale);
            tvGoodDetails.setAlpha(scale);
            llTitle.setAlpha(scale);
            if (scale >= 0.33) {
                goods_line.setVisibility(View.VISIBLE);
            } else {
                goods_line.setVisibility(View.INVISIBLE);
            }
        } else {    //滑动到banner下面设置普通颜色
            llTitle.setAlpha(1);
        }

        //上滑悬停
        int[] location = new int[2];
        radioGroup.getLocationInWindow(location);
        int xPosition = location[0];
        int yPosition = location[1];
        if (yPosition <= SizeUtils.dp2px(75)) {
//            radioGroupGone.setVisibility(View.VISIBLE);
            radioButton1.setClickable(false);
            radioButton2.setClickable(false);
        } else {
//            radioGroupGone.setVisibility(View.GONE);
            radioButton1.setClickable(true);
            radioButton2.setClickable(true);
        }

        //滑动关联
        int[] location1 = new int[2];
        int[] location2 = new int[2];
        goodsComment.getLocationInWindow(location1);
        llOffset.getLocationInWindow(location2);
        int yPosition1 = location1[1];
        int yPosition2 = location2[1];
        //控制商品，评价，详情在屏幕上移动的位置，从而改变它们的显示状态
        if (yPosition1 <= SizeUtils.dp2px(90)) {
            tvGoodComment.setTextColor(getResources().getColor(R.color.mall_color_blue));//改变颜色
            tvGoodComment.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));//改变粗细
            comment_line.setVisibility(View.VISIBLE);//下划线是否可见
            tvGoodTitle.setTextColor(getResources().getColor(R.color.light_text_color));
            tvGoodTitle.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            goods_line.setVisibility(View.INVISIBLE);
        } else if (yPosition2 <= SizeUtils.dp2px(90)) {
            tvGoodTitle.setTextColor(getResources().getColor(R.color.mall_color_blue));
            tvGoodTitle.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            goods_line.setVisibility(View.VISIBLE);
            tvGoodComment.setTextColor(getResources().getColor(R.color.light_text_color));
            tvGoodComment.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            comment_line.setVisibility(View.INVISIBLE);
        }

        //滑动关联
        int[] location3 = new int[2];
        radioGroup.getLocationInWindow(location3);
        int yPosition3 = location3[1];
        //控制商品，评价，详情在屏幕上移动的位置，从而改变它们的显示状态
        if (yPosition3 <= SizeUtils.dp2px(90)) {
            tvGoodComment.setTextColor(getResources().getColor(R.color.light_text_color));
            tvGoodComment.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            comment_line.setVisibility(View.INVISIBLE);
            tvGoodDetails.setTextColor(getResources().getColor(R.color.mall_color_blue));
            tvGoodDetails.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
            details_line.setVisibility(View.VISIBLE);
        } else if (yPosition2 <= SizeUtils.dp2px(90)) {
            tvGoodDetails.setTextColor(getResources().getColor(R.color.light_text_color));
            tvGoodDetails.setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
            details_line.setVisibility(View.INVISIBLE);
        }

    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        //收藏
        if (id == R.id.ll_favor) {
            //判断是否收藏
            if (isLove) {
                addOrRemoveCollect("remove");
            } else {
                addOrRemoveCollect("add");
            }
            //加入购物车
        } else if (id == R.id.tv_shopcart) {
            showSkuDialog(2);
            //立即购买
        } else if (id == R.id.tv_buy) {
            showSkuDialog(1);
            //夺宝
        } else if (id == R.id.tv_win_treasure) {
            showSkuDialog(3);
            //购物车
        } else if (id == R.id.ll_shopcart) {
            try {
                Bundle bundle = new Bundle();
                bundle.putBoolean(EFTransformFragmentActivity.EXTRA_HIDE_TITLE_BAR, true);
                EFFrameUtils.pushFragment((Class<? extends BaseFragment>) Class.forName("com.efounder.fragment.MallCartFragment"), bundle);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            //配送
        } else if (id == R.id.peisong) {
            final BottomDialog dialog = new BottomDialog(this);
            dialog.setOnAddressSelectedListener(new OnAddressSelectedListener() {
                @Override
                public void onAddressSelected(Province province, City city, County county, Street street) {
                    tvAddress.setText(ResStringUtil.getString(R.string.mail_to) + province.name + city.name);
                    dialog.dismiss();
                }
            });
            dialog.show();
            //评论
        } else if (id == R.id.goodscomment) {
            if (commentDatas == null) {
                ToastUtils.showShort(R.string.mall_request_comment_fail);
                return;
            }
            Intent intent = new Intent(ProductDetailsActivity.this, CommentActivity.class);
            intent.putExtra("goodbh", detailsDatas.getGood().getGoodId());
            intent.putExtra("count", commentDatas.getCommentCount());
            intent.putExtra("isCollection", isLove);
            double goodPrice = detailsDatas.getGood().getMallGoodPrice().getPrice();
            intent.putExtra("goodPrice", goodPrice);
            startActivityForResult(intent, 1);
            //分享商品
        } else if (id == R.id.iv_good_detai_share) {
            if (detailsDatas == null) {
                return;
            }
            DetailsDatas.GoodBean good1 = detailsDatas.getGood();
            MallPopManager.showMallSharePop(this, iv_good_detai_share, good1.getGoodId(),
                    good1.getGoodCover(), good1.getGoodName(), currentPrice.getText().toString().replace("", ""));
//            try {
//                DetailsDatas.GoodBean good1 = detailsDatas.getGood();
//                JSONObject goodObject = new JSONObject();
//                goodObject.put("goodId", String.valueOf(good1.getGoodId()));
//                goodObject.put("goodCover", good1.getGoodCover());
//                goodObject.put("title", good1.getGoodName());
//                goodObject.put("price", currentPrice.getText().toString().replace("", ""));
//                goodObject.put("from", ResStringUtil.getString(R.string.mall_from));
//                goodObject.put("shopIcon", "https://panserver.solarsource.cn/panserver/files/2c6a7eda-7995-4bd6-828b-4ba9b4d2c163/download");
//                ReflectUtils reflectUtils = ReflectUtils.reflect("com.efounder.MallShareHelper");
//                reflectUtils.newInstance().method("shareWithOtherParams", this, good1.getGoodUrl(), good1.getGoodName(), -1, "", goodObject.toString(), null);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
            //选择商品规格
        } else if (id == R.id.re_choose_sku) {
            //如果是虚拟商品只显示立即购买
            if(detailsDatas.getGood().getTypeBh().equals(GOOD_TYPE_VIRTUAL)||detailsDatas.getGood().getTypeBh().equals(GOOD_TYPE_NEW_VIRTUAL)){
                showSkuDialog(1);
                //限时抢购
            } else if (detailsDatas.getGood().getTypeBh().equals(GOOD_TYPE_TIME_TO_BUY)) {
                //已结束，sku显示已结束按钮
                if (detailsDatas.getGood().getTimeToBuyStatus() == STATUS_BUG_END) {
                    showSkuDialog(5);
                    //尚未开始，SKU显示尚未开始按钮
                } else if (detailsDatas.getGood().getTimeToBuyStatus() == STATUS_NO_START){
                    showSkuDialog(4);
                }
            } else {
                showSkuDialog(0);
            }

        } else if (id == R.id.tv_network_reload) {
//            重新加载
            getGoodsDetails(goodbh);
            getGoodsComments(goodbh);
        } else if (id == R.id.ll_custom_service) {
            //todo 通过商铺编号，客服id来跳转聊天
            LoadingDataUtilBlack.show(ProductDetailsActivity.this);
            Intent intent = new Intent();
            //FGT助手213092
            intent.putExtra("id", detailsDatas.getGood().getMallShop().getShopImUserid());
            intent.putExtra("chattype", StructFactory.TO_USER_TYPE_PERSONAL);
            ChatActivitySkipUtil.startChatActivity(ProductDetailsActivity.this, intent);
        }

    }

    /**
     * 跳转创建订单
     *
     * @param num   商品数量
     * @param skuId skuId
     */
    private void toCreateOrder(int num, String skuId) {
        Intent intent = new Intent(ProductDetailsActivity.this, CreateOrderActivity.class);
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("goodbh", goodbh);
            jsonObject.put("goodNum", num + "");
            jsonObject.put("skuId", skuId);
            //如果是新的虚拟商品  添加主钱包地址到json中
            if(detailsDatas.getGood().getTypeBh().equals(GOOD_TYPE_NEW_VIRTUAL)){
                jsonObject.put("mainAddress", EnvironmentVariable.getProperty("tc_ethAddress", ""));
            }
            JSONArray array = new JSONArray();
            array.put(jsonObject);
            intent.putExtra("checkItems", array.toString());
            startActivity(intent);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    public void addToCart(String goodbh, String goodNum, String skuId, final View view) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("goodbh", goodbh);
        map.put("skuId", skuId);
        map.put("goodNum", goodNum);
        MallRequestUtil.getRequest(TAG, GOOD_ADDTOCART_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    if ("success".equals(object.getString("result"))) {
                        int goodTotalCount = object.optInt("goodTotalCount");
                        startAnim(view, goodTotalCount);
                    } else if ("fail".equals(object.optString("result"))) {
                        ToastUtils.showShort(object.optString("msg"));
                    } else {
                        ToastUtils.showShort(R.string.mail_join_car_fail);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(ProductDetailsActivity.this, R.string.mail_join_car_fail, Toast.LENGTH_LONG).show();
                }
            }

            @Override
            public void onFail(String error) {
                Toast.makeText(ProductDetailsActivity.this, R.string.mail_join_car_fail, Toast.LENGTH_LONG).show();
            }
        });
    }

    /**
     * 请求网络获取商品详情
     *
     * @param goodbh 商品编号
     */
    public void getGoodsDetails(String goodbh) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("goodbh", goodbh);
        LoadingDataUtilBlack.show(ProductDetailsActivity.this);
        MallRequestUtil.getRequest(TAG, MallRequestUtil.GOOD_DETAIL_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                LoadingDataUtilBlack.dismiss();
                if (response != null && response.length() > 0) {
                    initDetailsData(response);
                } else {
                    llNetworkErrorView.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFail(String error) {
                LoadingDataUtilBlack.dismiss();
                llNetworkErrorView.setVisibility(View.VISIBLE);
            }
        });
    }

    /**
     * 修改购物车数量
     */
    public void addOrRemoveCollect(final String type) {
        HashMap<String, String> map = new HashMap<>();
        map.put("userId", EnvironmentVariable.getUserName());
        map.put("goodBhs", goodbh);
        map.put("operate", type);
        MallRequestUtil.getRequest(TAG, GOOD_COLLECT_AOR, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getString("result").equals("success")) {
                        if ("add".equals(type)) {
                            iv_shoucang.setImageDrawable(getResources().getDrawable(R.drawable.mall_favorite_selected));
                            tv_shoucang.setText(R.string.mail_collectioned);
                            isLove = true;
                            Collection.setLove(true);
                            ToastUtils.showShort(R.string.mail_collectioned);
                        } else if ("remove".equals(type)) {
                            iv_shoucang.setImageDrawable(getResources().getDrawable(R.drawable.mall_favorite_unselected));
                            tv_shoucang.setText(R.string.mail_collection);
                            isLove = false;
                            Collection.setLove(false);
                            ToastUtils.showShort(R.string.mall_collection_cancel);
                        }

                    } else {
                        Toast.makeText(ProductDetailsActivity.this, jsonObject.getString("msg"), Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    ToastUtils.showShort(R.string.mall_collect_fail);
                }

            }

            @Override
            public void onFail(String error) {
                ToastUtils.showShort(R.string.mall_collect_fail);
            }
        });
    }

    /**
     * 请求网络获取评论数据
     *
     * @param goodbh 商品编号
     */
    public void getGoodsComments(String goodbh) {
        HashMap<String, String> map = new HashMap<>();
        map.put("goodbh", goodbh);
        map.put("num", "0");
        map.put("pageSize", "10");
        MallRequestUtil.getRequest(TAG, GOOD_COMMENT_URL, map, new MallRequestUtil.MallRequestCallback() {
            @Override
            public void onSuccess(String response) {
                if (response != null && response.length() > 0) {
                    try {
                        Gson gson = new GsonBuilder().serializeNulls().create();
                        commentDatas = gson.fromJson(response, CommentDatas.class);
                        if (commentDatas.getResult().equals("success")) {
                            commentCount.setText(getString(R.string.mail_shop_assess) + commentDatas.getCommentCount() + ")");
                            commentPercent.setText(getString(R.string.mail_good_assess) + commentDatas.getCommentPercent() + ")");
                            if (commentDatas.getComments().size() == 0) {
                                cRecyclerView.setVisibility(View.GONE);
                            } else {
                                //设置布局管理器
                                LinearLayoutManager linearLayoutManager1 = new LinearLayoutManager(getApplicationContext());
                                linearLayoutManager1.setOrientation(LinearLayoutManager.HORIZONTAL);
                                cRecyclerView.setLayoutManager(linearLayoutManager1);
                                //设置适配器（商品评价）
                                ScrollAdapter mAdapterComment = new ScrollAdapter(commentDatas, detailsDatas, ProductDetailsActivity.this, R.layout.item_scroll_comments);
                                mAdapterComment.addFootView(new View(getApplicationContext()));
                                cRecyclerView.setAdapter(mAdapterComment);
                            }

                        } else {
                            ToastUtils.showShort(R.string.mall_request_comment_fail);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        ToastUtils.showShort(R.string.mall_request_comment_fail);
                    }
                }
            }

            @Override
            public void onFail(String error) {
                ToastUtils.showShort(R.string.mall_request_comment_fail);
            }
        });
    }

    /**
     * 处理商品详情数据
     */
    private void initDetailsData(String response) {
        try {
            Gson gson = new GsonBuilder().serializeNulls().create();
            detailsDatas = gson.fromJson(response, DetailsDatas.class);
            if (detailsDatas.getResult().equals("success")) {
                llNetworkErrorView.setVisibility(View.GONE);
                setDetailsDatas();
            } else {
                llNetworkErrorView.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void setDetailsDatas() {

        if (GOOD_TYPE_TREASURE.equals(detailsDatas.getGood().getTypeBh())) {
            isTreasureGood = true;
            currentPrice.setTextColor(getResources().getColor(R.color.mall_color_yellow));
            llGoodDetailService.setVisibility(View.GONE);
            tvWinTreasure.setVisibility(View.VISIBLE);
            llWinTreasureProgress.setVisibility(View.VISIBLE);
            int stock = detailsDatas.getTreasureBean().getData().getGoodsInfo().getStockSize();
            int total = detailsDatas.getTreasureBean().getData().getGoodsInfo().getTotal();
            int progress = (total - stock) * 100 / total;
            tvProgressNum.setText(String.format(ResStringUtil.getString(R.string.mall_treasure_progress),
                    total - stock));
            tvProgress.setText(progress + "%");

            tvOriginPrice.setVisibility(View.VISIBLE);
            tvOriginPrice.setText(String.format(ResStringUtil.getString(R.string.mall_treasure_origin_price),
                    String.valueOf(TCMathUtil.retainAsignDecimalsWithZero
                            ((detailsDatas.getGood().getMallGoodPrice().getTagPrice()), 2))));
            progressbar.setMax(100);
            progressbar.setProgress(progress);
            //限时抢购商品，显示已结束，开始时间，结束时间等
        }else {
            if (GOOD_TYPE_TIME_TO_BUY.equals(detailsDatas.getGood().getTypeBh())){
                findViewById(R.id.cl_time_to_buy).setVisibility(View.VISIBLE);
                ((TextView)findViewById(R.id.tv_start_time)).setText(TimeUtils.millis2String(Long
                        .valueOf(detailsDatas.getGood().getStartTime())));
                ((TextView)findViewById(R.id.tv_end_time)).setText(TimeUtils.millis2String(Long
                        .valueOf(detailsDatas.getGood().getEndTime())));
                if (GOOD_TYPE_TIME_TO_BUY.equals(detailsDatas.getGood().getTypeBh())){
                    if (detailsDatas.getGood().getTimeToBuyStatus() == STATUS_BUG_END) {
                        buyNow.setText(R.string.mall_end);
                        buyNow.setEnabled(false);
                    } else if (detailsDatas.getGood().getTimeToBuyStatus() == STATUS_NO_START){
                        buyNow.setText(R.string.mall_not_start);
                        buyNow.setEnabled(false);
                    } else {
                        buyNow.setEnabled(true);
                    }
                }
            }
            currentPrice.setTextColor(getResources().getColor(R.color.mall_color_blue));
            llGoodDetailService.setVisibility(View.VISIBLE);
        }


        //显示隐藏加入购物车按钮
        if(detailsDatas.getGood().getEnableAddCart() == 0){
            shopCart.setVisibility(View.GONE);
        } else {
            shopCart.setVisibility(View.VISIBLE);
        }

        //设置price
        currentPrice.setText(detailsDatas.getGood().getMallGoodPrice().getPriceUnit() + " " + TCMathUtil.retainAsignDecimalsWithZero(detailsDatas.getGood().getMallGoodPrice().getPrice(), 2));
//        设置商品sku
        List<GoodSkusBean> skuList = detailsDatas.getGood().getGoodSkus();
        if (skuList.size() > 0) {
            hasSku = true;
            if (!isTreasureGood) {
                reChooseSku.setVisibility(View.VISIBLE);
            }
            StringBuilder skuAttrs = new StringBuilder();
            for (int i = 0; i < skuList.get(0).getAttributeContentList().size(); i++) {
                skuAttrs.append(skuList.get(0).getAttributeContentList().get(i).getPIdName())
                        .append(" ");
            }
            tvSkuAttrs.setText(skuAttrs.toString());
        }
        if (detailsDatas.getIsCollection() == 0) {
            iv_shoucang.setImageDrawable(this.getResources().getDrawable(R.drawable.mall_favorite_unselected));
            tv_shoucang.setText(R.string.mail_collection);
            isLove = false;
            Collection.setLove(false);
        } else {
            iv_shoucang.setImageDrawable(this.getResources().getDrawable(R.drawable.mall_favorite_selected));
            tv_shoucang.setText(R.string.mail_collectioned);
            isLove = true;
            Collection.setLove(true);
        }

        title.setText(detailsDatas.getGood().getGoodName());
        tv_description.setText(detailsDatas.getGood().getDescription());
        getGoodCoverBitmap();
        initImagesPage();
        initFragment1();
    }

    private void getGoodCoverBitmap() {
        CommonThreadPoolUtils.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    bitmap = Glide.with(ProductDetailsActivity.this).asBitmap().load(detailsDatas.getGood().getGoodCover())
                            .into(100, 100)
                            .get();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void initImagesPage() {
        list = new ArrayList<>();
        if (detailsDatas.getGood().getPictures().size() == 0) {
            return;
        }
        for (int i = 0; i < detailsDatas.getGood().getPictures().size(); i++) {
            list.add(detailsDatas.getGood().getPictures().get(i).getPicUrl());
        }

        //初始化PagerAdapter
        PagerAdapter adapter = new PagerAdapter() {
            @Override
            public int getCount() {
                return detailsDatas.getGood().getPictures().size() + 1;
            }

            @Override
            public boolean isViewFromObject(View arg0, Object arg1) {
                return arg0 == arg1;
            }

            @Override
            public void destroyItem(ViewGroup container, int position, Object o) {
            }

            @Override
            public Object instantiateItem(ViewGroup container, final int position) {
                if (position < detailsDatas.getGood().getPictures().size()) {
                    ImageView im = new ImageView(ProductDetailsActivity.this);
                    imageLoader.displayImage(ProductDetailsActivity.this, detailsDatas.getGood().getPictures().get(position).getPicUrl(), im);
                    container.addView(im);
                    im.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            Intent intent = new Intent();
                            intent.putStringArrayListExtra("pic", list);
                            intent.putExtra("position", position);
                            intent.setClass(ProductDetailsActivity.this, ImageActivity.class);
                            startActivity(intent);
                        }
                    });
                    return im;
                } else {
                    View hintView = LayoutInflater.from(container.getContext()).inflate(R.layout.more_view, container, false);
                    container.addView(hintView);
                    return hintView;
                }

            }
        };
        viewPager.setAdapter(adapter);
        if (mLinearLayout.getChildCount() <= 0) {
            for (int i = 0; i < detailsDatas.getGood().getPictures().size(); i++) {
                //创建底部指示器(小圆点)
                View view = new View(this);
                view.setBackgroundResource(R.drawable.circlebg);
                view.setEnabled(false);
                //设置宽高
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(20, 20);
                //设置间隔
                if (i != 0) {
                    layoutParams.leftMargin = 30;
                }
                //添加到LinearLayout
                mLinearLayout.addView(view, layoutParams);

            }
        }
        //默认显示第一个指示器
        setIndicator(60, 0, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        getGoodsDetails(goodbh);//调用接口获取详情页数据
        getGoodsComments(goodbh);//获取评论
        initBadge();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            isLove = data.getExtras().getBoolean("result", false);//得到新Activity 关闭后返回的数据
            if (!isLove) {
                iv_shoucang.setImageDrawable(this.getResources().getDrawable(R.drawable.mall_favorite_unselected));
                tv_shoucang.setText(R.string.mail_collection);
                isLove = false;
                Collection.setLove(false);
            } else {
                iv_shoucang.setImageDrawable(this.getResources().getDrawable(R.drawable.mall_favorite_selected));
                tv_shoucang.setText(R.string.mail_collectioned);
                isLove = true;
                Collection.setLove(true);
            }
        }
    }

    /**
     * 弹出SKU选择
     *
     * @param showSkuType 0表示只返回更新界面，
     *                    1是点立即购买，返回即跳订单界面，
     *                    2表示加入购物车
     *                    3 表示夺宝，传入的价格等数值要从夺宝bean里取
     *                    4 表示限时抢购，尚未开始
     *                    5 表示限时抢购，已结束
     */
    private void showSkuDialog(final int showSkuType) {
        if (dialog == null) {
            dialog = new ProductSkuDialog(this);
        }
        //夺宝商品，只需要价格和库存
        if (showSkuType == 3) {
            GoodSkusBean goodSkusBean = detailsDatas.getGood().getGoodSkus().get(0);
            goodSkusBean.setStockNumber(detailsDatas.getTreasureBean().getData().getGoodsInfo().getStockSize());
            dialog.setData(detailsDatas.getGood(), selectedSku, true, new ProductSkuDialog.Callback() {
                @Override
                public void onAdded(GoodSkusBean sku, int quantity) {
                    //夺宝商品只有立即购买这一步
                    toCreateOrder(quantity, sku.getSkuId());
                }

                @Override
                public void onBuy(GoodSkusBean skusBean, int quantity) {

                }

                @Override
                public void onAddToCart(GoodSkusBean skusBean, int quantity) {

                }
            });
        } else {
            dialog.setData(detailsDatas.getGood(), selectedSku, false, new ProductSkuDialog.Callback() {

                @Override
                public void onBuy(GoodSkusBean skusBean, int quantity) {
                    //直接购买
                    selectedSku = skusBean;
                    if (selectedSku != null) {
                        setUpUIAfterSkuCallback();
                        toCreateOrder(quantity, selectedSku.getSkuId());
                    }
                }

                @Override
                public void onAddToCart(GoodSkusBean skusBean, int quantity) {
                    //加入购物车
                    selectedSku = skusBean;
                    if (selectedSku != null) {
                        setUpUIAfterSkuCallback();
                        addToCart(goodbh, String.valueOf(quantity), selectedSku.getSkuId(), shopCart);
                    }
                }

                @Override
                public void onAdded(GoodSkusBean sku, int quantity) {
                    //确定按钮，根据传过来的值选择购买还是加购物车
                    selectedSku = sku;
                    if (selectedSku != null) {
                        setUpUIAfterSkuCallback();
                        if (showSkuType == 1) {
                            //立即购买
                            toCreateOrder(quantity, selectedSku.getSkuId());
                        } else if (showSkuType == 2) {
                            //加购物车
                            addToCart(goodbh, String.valueOf(quantity), selectedSku.getSkuId(), shopCart);
                        }
                    }
                }
            });
        }
        dialog.setButton(showSkuType);
        dialog.show();
    }

    /**
     * SKU选择回调后设置界面
     */
    private void setUpUIAfterSkuCallback() {
        List<GoodSkusBean.AttributeContentListBean> attrList =
                selectedSku.getAttributeContentList();
        StringBuilder attrBuilder = new StringBuilder();
        for (int i = 0; i < attrList.size(); i++) {
            attrBuilder.append(attrList.get(i).getVIdName())
                    .append(" ");
        }
        tvChooseSkuHint.setText(R.string.mall_sku_selected);
        tvSkuAttrs.setVisibility(View.VISIBLE);
        tvSkuAttrs.setText(attrBuilder.toString());
        currentPrice.setText(detailsDatas.getGood().getMallGoodPrice().getPriceUnit() + " " + TCMathUtil.retainAsignDecimalsWithZero(selectedSku.getSkuPrice(), 2));
        title.setText(selectedSku.getPropertiesName());
    }

    @Override
    protected void onStop() {
        super.onStop();
        EFHttpRequest.cancelRequest(TAG);
    }

    @Override
    public boolean immersionBarEnabled() {
        return true;
    }
}
